#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
unsigned char realGrayIndex[256];
struct huffmanNode
{
	int weight;
	int llink;//-1时说明该分支没孩子
	int rlink;//-1时说明该分支没孩子
	int flink;//父结点，为-1时说明是根
}*HuffTree[512];
struct huffmancode
{
    unsigned char c;
    int len;
    unsigned char code[256];
}Huffmap[256];
int Treefind(int root_id,unsigned char now_code)
{
    unsigned int icode=now_code;//强制类型转换
    int bit=0,treeindex=root_id;
    while(bit<8)
    {
        if(HuffTree[treeindex]->llink==-1&&HuffTree[treeindex]->rlink==-1)break;
        if(icode%2==0)
        {
            treeindex=HuffTree[treeindex]->llink;
        }
        else treeindex=HuffTree[treeindex]->rlink;
        bit++;
        icode=icode>>1;
    }
    return treeindex;

}
void unzip(FILE *fp,int realGraynum,int width,int height,unsigned char *bufOUT)
{
    int root_id=2*realGraynum-2;
    unsigned char now_code;
    for(int i=0;i<height;i++)
        for(int j=0;j<width;j++)
        {
            fread(&now_code,sizeof(unsigned char),1,fp);
            int be_index=Treefind(root_id,now_code);
            bufOUT[i*width+j]=realGrayIndex[be_index];//???我不是很明白realGrayIndex是不是这个意思，但是解码完了图像是乱的；
            //我认为谢凤英的压缩程序就有问题，它生成的这个.huff文件里面huffman树的叶子结点没有保存原来的字符，不能还原。
        }
}
int main()
{
    int realGraynum,width,height;
    FILE *fp;
    for(int k=1;k<=69;k++)
    {
        string filename="/Users/yuzhengze/Documents/C++/数据结构/Huffman_XIE/图像集 - 给学生/";
        filename+=to_string(k);
        filename+=".huff";
        fp=fopen(filename.c_str(),"rb");
        fread(&realGraynum,sizeof(int),1,fp);
        fread(realGrayIndex,sizeof(unsigned char),realGraynum,fp);
        for(int i=0;i<2*realGraynum-1;i++)
        {    
            HuffTree[i]=new huffmanNode;
            fread(&HuffTree[i]->weight,sizeof(int),1,fp);
            fread(&HuffTree[i]->llink,sizeof(int),1,fp);
            fread(&HuffTree[i]->rlink,sizeof(int),1,fp);
            fread(&HuffTree[i]->flink,sizeof(int),1,fp);
        }
        fread(&width,sizeof(int),1,fp);
        fread(&height,sizeof(int),1,fp);
        cout<<"realGraynum:"<<realGraynum<<endl;
        cout<<"width:"<<width<<endl;
        cout<<"height:"<<height<<endl;
        unsigned char *bufOUT=new unsigned char[width*height];
        unzip(fp,realGraynum,width,height,bufOUT);
        FILE *w_fp;
        filename="/Users/yuzhengze/Documents/C++/数据结构/Huffman_XIE/图像集 - 给学生/";
        filename+=to_string(k);
        filename+=".raw";
        w_fp=fopen(filename.c_str(),"wb");
        fwrite(bufOUT,sizeof(unsigned char),width*height,w_fp);
        fclose(fp);
        fclose(w_fp);
        delete[] bufOUT;
    }
    return 0;
}